/*java中设置图片自适应Jlable的大小*/
package com.component;
 
import javax.swing.*;

import com.view.P3;

import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
 
public class ImageLabel  extends JPanel {
	private JLabel jlb = new JLabel();
	
	private int width = 488, height = 418;
	private String url;
	public ImageLabel() {
		this.setSize(width, height);
		setLayout(null);
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 10, width, height);
		add(scrollPane);
		scrollPane.setViewportView(jlb);
		this.setVisible(true);
		setUrl();
	}
	
	public void setUrl() {
		ImageIcon image = null;
		this.url="https://i0.hdslb.com/bfs/archive/16ad7f08e2ae159b1d8fbf0abb71decb85535b0d.jpg";
		try {
			if(url.indexOf("http")==-1) {
        		image = new ImageIcon(url);
        	}else {
        		image = new ImageIcon(new URL(url));
        	}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		int iconWidth = image.getIconWidth();
		int iconHeight = image.getIconHeight();
		this.height = iconHeight / (iconWidth / width);
		Image img = image.getImage();
		img = img.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
		image.setImage(img);
		jlb.setIcon(image);
	}
	public static void main(String[] args) {
		util.GUIUtil.showPanel(new ImageLabel());
	}
}
